import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Types } from 'mongoose';
import { getFormatDate } from 'src/utils';
import { RecordWay, Unit, SetsType } from 'src/types/motion';

@Schema({
  collection: 'records',
  validateBeforeSave: true,
  versionKey: false,
  timestamps: true,
})
export class Record extends Document {
  @Prop({
    type: String,
    default: () => getFormatDate(),
    index: true,
    required: true,
    validate: {
      validator: (v: string) => /^\d{4}-\d{2}-\d{2}$/.test(v),
      message: '日期格式必须为 YYYY-MM-DD',
    },
  })
  date: string;

  @Prop({
    type: Types.ObjectId,
    ref: 'Motion',
    required: true,
    index: true,
  })
  motionId: Types.ObjectId;

  @Prop({ type: Number, enum: RecordWay, default: RecordWay.sets })
  recordWay?: RecordWay;

  @Prop({ type: Number, enum: SetsType, default: SetsType.reps })
  setsType?: SetsType;

  @Prop({
    type: Number,
    enum: Unit,
    default: Unit.kg,
  })
  unit?: Unit;

  @Prop({
    type: Array<[Number, Number]>,
    default: [],
  })
  sets?: [number, number][];

  @Prop({
    type: Number,
    default: 0,
  })
  takeTime?: number;

  @Prop({
    type: Types.ObjectId,
    ref: 'User',
    required: true,
    index: true,
  })
  userId: Types.ObjectId;
}

export const RecordSchema = SchemaFactory.createForClass(Record);

// 复合索引优化
RecordSchema.index({ userId: 1, date: 1 });
RecordSchema.index({ userId: 1, motionId: 1 });
